package org.summer.gateway.handler;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.summer.common.http.Result;
import org.summer.common.http.ResultCode;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局异常处理
 * @author wjj9132
 * @date 2024/9/25 15:33
 * @since 1.0
 */
@Log4j2
@Order(-1)
@Component
@RequiredArgsConstructor
public class GlobalExceptionHandler implements ErrorWebExceptionHandler {
    private final ServerResponseHandler responseHandler;

    @Override
    public Mono<Void> handle(@NonNull ServerWebExchange exchange,@NonNull Throwable ex) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.INTERNAL_SERVER_ERROR);
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        log.error("网关系统异常",ex);
        Result<String> result = Result.fail(ResultCode.INTERNAL_SERVER_ERROR, ex.getMessage());
        return responseHandler.handlerResponse(exchange,result);
    }
}
